﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using Portal.Systems.Model;
using Portal.Database.Service;
using Portal.Web.Utility;
using Portal.Core;
using Portal.Systems.Bussiness.Template;
using System.Collections.ObjectModel;
using System.Collections;
using Portal.Utility;

namespace Portal.Systems.Bussiness
{
    public class RoleProcessBll
    {
        public static RoleCls[] ReadingRoles(string SiteId, string RoleType, string Keyword)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select TableRole.*,TotalUsers=(select count(UserRoleId) from TableUserRole  where frkRoleId=RoleId) from TableRole where 1=1 ";
            if (!string.IsNullOrEmpty(RoleType))
            {
                Query += " and RoleId in (select RoleId from TableRoleAccountType where AccountType='" + RoleType + "') ";
            }
            if (!string.IsNullOrEmpty(Keyword))
            {
                Query += " and (RoleCode like N'%" + Keyword + "%' or RoleName like N'%" + Keyword + "%')";
            }
            Query +=
                   "     and AssetCode=@AssetCode order by RoleCode";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] CmsAccount = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsAccount;
        }



        public static RoleCls[] ReadingRolesForDatabaseFolderPermission(
            string SiteId, 
            string DatabaseFolderId, 
            string Keyword)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            Keyword = FunctionUtilities.CorrectForSearch(Keyword);
            string Query =
                " select TableRole.*,TotalUsers=(select count(UserRoleId) from TableUserRole  where frkRoleId=RoleId) from TableRole where RoleId not in (select frkRoleId from TableDatabaseFolderPermission where frkDatabaseFolderId=@DatabaseFolderId) ";
            if (!string.IsNullOrEmpty(Keyword))
            {
                Query += " and (RoleCode like N'%" + Keyword + "%' or RoleName like N'%" + Keyword + "%')";
            }
            Query +=
                   "     and AssetCode=@AssetCode order by RoleCode";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DatabaseFolderId", DatabaseFolderId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] CmsAccount = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsAccount;
        }



        public static RoleCls[] ReadingRolesForDatabaseFieldPermission(
            string SiteId,
            string DatabaseFieldId,
            string Keyword)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            Keyword = FunctionUtilities.CorrectForSearch(Keyword);
            string Query =
                " select TableRole.*,TotalUsers=(select count(UserRoleId) from TableUserRole  where frkRoleId=RoleId) from TableRole where RoleId not in (select frkRoleId from TableDatabaseFieldPermission where frkDatabaseFieldId=@DatabaseFieldId) ";
            if (!string.IsNullOrEmpty(Keyword))
            {
                Query += " and (RoleCode like N'%" + Keyword + "%' or RoleName like N'%" + Keyword + "%')";
            }
            Query +=
                   "     and AssetCode=@AssetCode order by RoleCode";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DatabaseFieldId", DatabaseFieldId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] CmsAccount = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsAccount;
        }


        public static RoleCls[] ReadingRolesForUser(string SiteId, string UserId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = OSiteParam.SiteCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select TableRole.* from TableUserRole " +
                "   join TableRole on TableRole.RoleId=frkRoleId " +
                "  where frkUserId=@UserId and AssetCode=@AssetCode order by RoleCode";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("UserId", UserId),
                        new DbParam("AssetCode", AssetCode),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] CmsAccount = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsAccount;
        }


        public static RoleCls CreateRoleModel(string SiteId, string RoleId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableRole where ( RoleId=@RoleId or RoleCode=@RoleId) ",
                    new DbParam[] 
                    { 
                        new DbParam("RoleId", RoleId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            RoleCls ORole = RoleParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return ORole;
        }


        public static string AddRole(
            string SiteId,
            string AssetCode,
            string RoleId,
            string RoleCode,
            string RoleName,
            string RoleType)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            if (string.IsNullOrEmpty(RoleId))
            {
                RoleId = System.Guid.NewGuid().ToString();
            }
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            IDbTransaction Trans = DBService.BeginTransaction();
            try
            {
                DBService.Insert(Trans, "TableRole",
                        new DbParam[] 
                    { 
                        new DbParam("RoleId", RoleId),
                        new DbParam("RoleCode", RoleCode),
                        new DbParam("RoleName", RoleName),
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                        new DbParam("EntryDate", System.DateTime.Now),
                    });
                DBService.Insert(Trans, "TableRoleAccountType",
                        new DbParam[] 
                    { 
                        new DbParam("RoleAccountTypeId", RoleId),
                        new DbParam("AccountType", RoleType),
                        new DbParam("RoleId", RoleId),
                    });

                Trans.Commit();
            }
            catch (Exception ex)
            {
                Trans.Rollback();
                throw (ex);
            }
            return RoleId;
        }


        public static void SaveRole(string SiteId, string RoleId, string LoginName, string FullName)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.Update(null, "TableRole", "RoleId", RoleId,
                    new DbParam[] 
                    { 
                        new DbParam("RoleCode", LoginName),
                        new DbParam("RoleName", FullName),
                    });
        }


        public static void DeleteRole(string SiteId, string RoleId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " Delete from TableRoleAccountType where RoleId=@RoleId; " +
                " Delete from TableUserRole where frkRoleId=@RoleId; " +
                " Delete from TableRoleInGroupRole where frkRoleId=@RoleId; " +
                " Delete from TableRole where RoleId=@RoleId; ";
            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("RoleId", RoleId),
                    });
        }


        public static Collection<UserCls> ReadingUserBelongRoleForWorkflow(string SiteId, string[] RoleIds)
        {
            Collection<UserCls> ColUsers = new Collection<UserCls> { };
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            if (RoleIds.Length == 0)
            {
                return ColUsers;
            }
            string RoleText = "(";
            for (int iIndex = 0; iIndex < RoleIds.Length; iIndex++)
            {
                RoleText = RoleText + "'" + RoleIds[iIndex] + "'";
                if (iIndex < RoleIds.Length - 1)
                {
                    RoleText = RoleText + ",";
                }
            }
            RoleText += ")";
            Hashtable hs = new Hashtable();
            DataTable dtRole =
                DBService.GetDataTable(null, "select RoleId,RoleName from TableRole where RoleId in " + RoleText, null);
            for (int iIndexRole = 0; iIndexRole < dtRole.Rows.Count; iIndexRole++)
            {
                string RoleId = (string)dtRole.Rows[iIndexRole]["RoleId"];
                string RoleName = (string)dtRole.Rows[iIndexRole]["RoleName"];
                DataSet dsResult =
                       DBService.GetDataSet(null, "select TableUser.* from TableUserRole join TableUser on TableUser.UserId=frkUserId where frkRoleId=@RoleId",
                        new DbParam[] 
                        { 
                            new DbParam("RoleId", RoleId),
                        });
                UserCls[] Users = UserParser.ParseFromDataTable(dsResult.Tables[0]);
                for (int iIndexUser = 0; iIndexUser < Users.Length; iIndexUser++)
                {
                    if (!Users[iIndexUser].LoginName.ToLower().Equals("SHAREPOINT\\system".ToLower()))
                    {
                        Users[iIndexUser].RoleId = RoleId;
                        Users[iIndexUser].RoleName = RoleName;

                        string Key = RoleId + "~" + Users[iIndexUser].UserId;
                        if (hs.ContainsKey(Key) == false)
                        {
                            ColUsers.Add(Users[iIndexUser]);
                            hs.Add(Key, Users[iIndexUser]);
                        }
                    }
                }
                dsResult.Clear();
            }
            return ColUsers;
        }


        
    }
}

